<template>
  <el-card class="editor-card">
    <el-form ref="articleForm" :model="form" :rules="rules" label-width="80px">
      <!-- 文章标题 -->
      <el-form-item label="标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入文章标题" />
      </el-form-item>

      <!-- 文章分类 -->
      <el-form-item label="分类" prop="category_id">
        <el-select v-model="form.categoryName" placeholder="请选择分类">
          <el-option
            v-for="category in categoryList"
            :key="category.id"
            :label="category.name"
            :value="category.id"
          />
        </el-select>
      </el-form-item>

      <!-- 文章标签 -->
      <el-form-item label="标签" prop="tags">
        <el-input
          v-model="form.tags"
          placeholder="多个标签用逗号分隔（如：Vue,前端）"
          @change="handleTagsChange"
        />
      </el-form-item>

      <!-- 文章内容（Markdown编辑器） -->
      <el-form-item label="内容" prop="content">
        <v-md-editor
          v-model="form.content"
          height="400px"
          :toolbar-config="toolbarConfig"
        />
      </el-form-item>

      <!-- 操作按钮 -->
      <el-form-item>
        <el-button type="primary" @click="handleSave">保存</el-button>
        <el-button @click="handleCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
// 移除重复的样式和主题导入（假设已在 main.js 中全局配置）
import {
  getCategoryList,
  getArticleDetail,
  postEditArticle,
  getCategoryName,
} from "@/api";

export default {
  data() {
    return {
      form: {
        id: null,
        title: "",
        categoryName: "",
        tags: "",
        content: "",
      },
      categoryList: [],
      rules: {
        title: [{ required: true, message: "请输入文章标题", trigger: "blur" }],
        category_id: [
          { required: true, message: "请选择文章分类", trigger: "change" },
        ],
        content: [
          { required: true, message: "请输入文章内容", trigger: "change" },
        ],
      },
      toolbarConfig: {
        pin: true,
        preview: true,
        fullscreen: true,
      },
    };
  },
  async mounted() {
    // 获取分类列表（不变）
    const res = await getCategoryList();
    this.categoryList = res.data.data;

    // 编辑模式加载详情（不变）
    const articleId = this.$route.params.id;
    if (articleId) {
      this.form.id = articleId;
      this.loadArticleDetail(articleId);
    }
  },
  methods: {
    // 加载文章详情（不变）
    async loadArticleDetail(articleId) {
      const res = await getArticleDetail(articleId);
      const categoryRes = await getCategoryName(res.data.data.category_id);
      console.log(res);
      this.form = {
        ...res.data.data,
        categoryName: categoryRes.data.data.name,
        tags: res.data.data.tags, // 标签数组转字符串（用逗号分隔）
      };
    },

    // 处理标签输入（自动去除多余逗号）
    handleTagsChange() {
      this.form.tags = this.form.tags.replace(/,+/g, ",").replace(/^,|,$/g, "");
    },
    // 保存文章
    async handleSave() {
      this.$refs.articleForm.validate(async (valid) => {
        if (!valid) return;
        const saveData = { ...this.form };

        try {
          const res = await postEditArticle(saveData);
          console.log(res);

          this.$message.success(this.form.id ? "文章更新成功" : "文章发布成功");
          this.$router.push("/my/article"); // 跳转回用户文章列表页
        } catch (err) {
          this.$message.error("保存失败：" + err.message);
        }
      });
    },
    // 取消编辑
    handleCancel() {
      this.$router.go(-1); // 返回上一页
    },
  },
};
</script>

<style scoped>
/* 保留原有样式（编辑器边框、卡片布局等） */
.editor-card {
  max-width: 1200px;
  margin: 20px auto;
  padding: 30px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.v-md-editor {
  border: 1px solid #ebeef5;
  border-radius: 4px;
  height: 400px;
  overflow: hidden;
  contain: strict; /* Limit browser layout calculations */
  min-height: 400px; /* Prevent shrinking below fixed height */
  max-height: 400px; /* Prevent expanding beyond fixed height */
}

.v-md-editor .v-md-content {
  height: 100%;
  overflow: auto;
  contain: content; /* Isolate content layout changes */
}
</style>
